<template>
  <div class="system-message-container">
    <div
      class="system-message"
      v-for="(message, index) in messages"
      :key="message.orderId"
      :class="{ 'read': message.read }"
    >
      <div class="message-header">
        <!-- index和message.orderId相同，替换了 -->
        <button @click="markAsRead(index)">标记已读</button>
        <!-- <button @click="markAsRead(message.orderId)">标记已读</button> -->
        <button @click="deleteMessageAction(message.orderId)">删除</button>
      </div>
      <div class="message-content">
        <p>订单已发货</p>
        <p>消息内容: {{ message.content }}</p>
        <p>时间: {{ message.time }}</p>
        <p>快递单号: {{ message.trackingNumber }}</p>
        <p>商家: {{ message.seller }}</p>
      </div>
      <button class="view-details" @click="viewDetails(message)">查看详情</button>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState(['messages'])
  },
  methods: {
    // 重命名为 `deleteMessageAction`，避免与 Vuex action 命名冲突
    ...mapActions(['deleteMessage']),
    
    markAsRead(index) {
        this.messages[index].read = true;
      // 标记消息为已读的逻辑
    },
    
    // 使用正确的方法调用 Vuex action
    deleteMessageAction(id) {
      this.deleteMessage(id);  // 调用 Vuex 删除消息的 action
    },

    // 确保 `orderId` 存在并跳转到 OrderDetails 页面
    viewDetails(message) {
      // alert(message.orderId)
      // orderId 0时不会执行，+1使得0也执行
      if (message.orderId+1) {
        this.$router.push({ name: 'OrderStatus', params: { orderindex: message.orderId } });
        
      } else {
        console.error('消息没有找到有效的订单 ID');
      }
    }
  }
};
</script>

<style scoped>
.system-message.read {
  background-color: lightgreen; /* 已读消息的背景颜色 */
}
.system-message-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.system-message {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  margin: 20px;
  width: 400px;
  background-color: #fff;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.system-message.read {
  background-color: #e9f7e9;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.message-content {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 15px;
}

.view-details {
  display: block;
  width: 100%;
  padding: 12px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  text-align: center;
  transition: background-color 0.3s;
}

.view-details:hover {
  background-color: #45a049;
}

button {
  padding: 5px 10px;
  cursor: pointer;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 14px;
}

button:hover {
  background-color: #45a049;
}
</style>
